package com.yfbao.horizon.user.injection.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.ShardingConnection;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SQLExecutionInterceptor {

    private final MeterRegistry meterRegistry;

    public SQLExecutionInterceptor(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    public PreparedStatement intercept(Connection connection, String sql) throws SQLException {
        Timer.Sample sample = Timer.start(meterRegistry);

        // 使用 Sharding-JDBC 的 PreparedStatement 执行 SQL
        PreparedStatement preparedStatement = new ShardingPreparedStatement((ShardingConnection)connection, sql);

        // 在 SQL 执行后停止计时，并记录到 Micrometer 中
        Timer timer = meterRegistry.timer("sharding_jdbc.sql.execution.time", "sql", sql);
        sample.stop(timer);

        return preparedStatement;
    }
}
